import { Component, OnInit, OnDestroy, ComponentFactoryResolver, ViewChild, Input } from '@angular/core'
import { WidgetDirective } from './widget.directive'
import { Widget, widgetDatas, WidgetProps } from './model'

// <ng-template> 动态加载组件提供的容器，我们需要将组件加载到容器中，则需要一个指令(Directive)来对容器进行标记
@Component({
  selector: 'widget-container',
  template: `
    <ng-template widgetHost></ng-template>
  `
})
export class WidgetComponent implements OnInit, OnDestroy {
  @Input() componentName = '' // 加载的组件名称
  @Input() componentsConfig = {} // 组件配置信息

  @ViewChild(WidgetDirective) widgetHost!: WidgetDirective // 通过 ViewChild 获取到 widgetHost 的实例

  constructor(private componentFactoryResolver: ComponentFactoryResolver) {}

  ngOnInit() {
    this.loadComponent()
  }

  ngOnDestroy() {}

  loadComponent() {
    const componentData = widgetDatas[this.componentName] as WidgetProps
    const componentsConfig = this.componentsConfig[this.componentName] || '' // 组件常用项目Id
    if (this.componentName && componentData) {
      // console.log('loadComponent：', this.componentName)
      componentData.componentsConfig = componentsConfig
      const component = componentData.component
      const componentFactory = this.componentFactoryResolver.resolveComponentFactory<Widget>(component) // ComponentFactory 用于创建组件实例的生成的类
      const viewContainerRef = this.widgetHost.viewContainerRef // viewContainerRef 作为容器加载组件
      viewContainerRef.clear()
      // 获取组件实例可以设置数据等操作
      const componentRef = viewContainerRef.createComponent<Widget>(componentFactory) // viewContainerRef 需要的是 ComponentFactory
      componentRef.instance.componentData = componentData
    }
  }
}
